<template>
  <div class="model-management">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="算法调优" name="tuning">
        <tuning-panel
          :models="models"
          :tuningTasks="tuningTasks"
          @start-tuning="handleStartTuning"
        />
      </el-tab-pane>
      <el-tab-pane label="AB测试" name="abtest">
        <abtest-panel
          :models="models"
          :abTests="abTests"
          @run-abtest="handleRunAbTest"
        />
      </el-tab-pane>
      <el-tab-pane label="模型服务化" name="serving">
        <serving-panel
          :models="models"
          :servingList="servingList"
          :users="users"
          @add-serving="handleAddServing"
          @update-serving="handleUpdateServing"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import TuningPanel from './tuningPanel.vue';
import AbtestPanel from './abtestPanel.vue';
import ServingPanel from './servingPanel.vue';

// mock数据生成
function getMockModels() {
  return [
    {
      id: 'm1',
      name: 'XGBoost-设备故障预测',
      type: 'XGBoost',
      params: { learning_rate: 0.1, n_estimators: 100 },
      desc: '用于设备故障预测的XGBoost模型',
      version: 'v1.0',
      history: [
        { version: 'v1.0', desc: '初始版本', time: '2024-06-01' }
      ],
      permissions: ['admin', 'userA']
    },
    {
      id: 'm2',
      name: 'LSTM-剩余寿命预测',
      type: 'LSTM',
      params: { layers: 3, units: 128 },
      desc: '用于设备剩余寿命预测的LSTM模型',
      version: 'v1.0',
      history: [
        { version: 'v1.0', desc: '初始版本', time: '2024-06-01' }
      ],
      permissions: ['admin']
    },
    {
      id: 'm3',
      name: '随机森林-异常检测',
      type: 'RandomForest',
      params: { n_estimators: 50, max_depth: 10 },
      desc: '用于异常检测的随机森林模型',
      version: 'v1.0',
      history: [
        { version: 'v1.0', desc: '初始版本', time: '2024-06-01' }
      ],
      permissions: ['admin', 'userB']
    }
  ];
}

function getMockUsers() {
  return [
    { id: 'admin', name: '管理员' },
    { id: 'userA', name: '用户A' },
    { id: 'userB', name: '用户B' }
  ];
}

// localStorage工具
const LS_KEY = 'model-management-data';
function loadData() {
  const data = JSON.parse(localStorage.getItem(LS_KEY));
  if (data) return data;
  // 首次加载写入mock
  const initData = {
    models: getMockModels(),
    tuningTasks: [],
    abTests: [],
    servingList: [],
    users: getMockUsers()
  };
  localStorage.setItem(LS_KEY, JSON.stringify(initData));
  return initData;
}
function saveData(data) {
  localStorage.setItem(LS_KEY, JSON.stringify(data));
}

export default {
  name: 'ModelManagement',
  components: {
    TuningPanel,
    AbtestPanel,
    ServingPanel
  },
  data() {
    const data = loadData();
    return {
      activeTab: 'tuning',
      models: data.models,
      tuningTasks: data.tuningTasks,
      abTests: data.abTests,
      servingList: data.servingList,
      users: data.users
    };
  },
  methods: {
    // 算法调优
    handleStartTuning({ modelId, params }) {
      const model = this.models.find(m => m.id === modelId);
      // mock调优过程
      const result = Math.random() > 0.5 ? '提升2%准确率' : '无明显提升';
      const task = {
        modelId,
        modelName: model.name,
        params,
        status: '已完成',
        result,
        time: new Date().toLocaleString()
      };
      this.tuningTasks.unshift(task);
      // 更新模型参数
      if (model.type === 'XGBoost') {
        model.params.learning_rate = params.learning_rate;
        model.params.n_estimators = params.n_estimators;
        // 记录历史
        model.history.push({
          version: model.version,
          desc: `调优：lr=${params.learning_rate}, n=${params.n_estimators}`,
          time: new Date().toLocaleDateString()
        });
      }
      this.saveAll();
      Message.success('调优任务已完成');
    },
    // AB测试
    handleRunAbTest({ modelIds, testData, metric }) {
      const models = this.models.filter(m => modelIds.includes(m.id));
      // mock结果
      const results = models.map(m => ({
        model: m.name,
        value: (Math.random() * 0.2 + 0.8).toFixed(3) // 0.8~1.0
      }));
      // 选最优
      const winner = results.reduce((a, b) => (a.value > b.value ? a : b)).model;
      const abTest = {
        models,
        metric,
        results,
        winner,
        time: new Date().toLocaleString()
      };
      this.abTests.unshift(abTest);
      this.saveAll();
      Message.success('AB测试已完成');
    },
    // 服务化
    handleAddServing({ modelId, apiInput, apiOutput, versionDesc, permissions }) {
      const model = this.models.find(m => m.id === modelId);
      const version = 'v' + (model.history.length + 1) + '.0';
      const serving = {
        modelId,
        modelName: model.name,
        apiInput,
        apiOutput,
        version,
        versionDesc,
        permissions: [...permissions],
        history: [
          ...model.history,
          { version, desc: versionDesc, time: new Date().toLocaleDateString() }
        ]
      };
      this.servingList.unshift(serving);
      // 更新模型历史和权限
      model.version = version;
      model.history.push({ version, desc: versionDesc, time: new Date().toLocaleDateString() });
      model.permissions = [...permissions];
      this.saveAll();
      Message.success('服务化封装成功');
    },
    handleUpdateServing(serving) {
      // 弹窗可扩展，这里直接模拟权限变更
      const newPermissions = prompt('请输入新的权限用户id（用,分隔）', serving.permissions.join(','));
      if (newPermissions !== null) {
        serving.permissions = newPermissions.split(',').map(s => s.trim());
        // 同步到模型
        const model = this.models.find(m => m.id === serving.modelId);
        if (model) model.permissions = [...serving.permissions];
        this.saveAll();
        Message.success('权限已更新');
      }
    },
    saveAll() {
      saveData({
        models: this.models,
        tuningTasks: this.tuningTasks,
        abTests: this.abTests,
        servingList: this.servingList,
        users: this.users
      });
    }
  }
};
</script>

<style scoped>
.model-management {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}
</style>
